package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorks;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
        implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private RedisIdWorks redisIdWorks;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("stream.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //    ThreadPoolExecutor test = new ThreadPoolExecutor(
//            10,
//            10,
//            10,
//            TimeUnit.SECONDS,
//            new ArrayBlockingQueue<>(10),
//            Executors.defaultThreadFactory(),
//            new ThreadPoolExecutor.AbortPolicy());
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    private IVoucherOrderService proxy;

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    /**
     * 获取消息队列消息 xreadgruop group g1 c1 count 1 block 2000 streams stream.orders > 成功：下单 失败：结束，下一次 ACK
     * 确认
     */
    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list =
                            stringRedisTemplate.opsForStream().read(
                                    Consumer.from("g1", "c1"),
                                    StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                                    StreamOffset.create(queueName, ReadOffset.lastConsumed()));

                    if (list == null || list.isEmpty()) {
                        continue;
                    }
                    // 解析订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    handleVoucherOrder(voucherOrder);
                    // ack   sack    stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0")));

                    if (list == null || list.isEmpty()) {
                        break;
                    }
                    // 解析订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    // ack   sack    stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pending-list异常", e);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }

    //
    //    //阻塞队列，队列无元素，阻塞，有元素被唤醒
    //    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    //    private class VoucherOrderHandler implements Runnable{
    //
    //        @Override
    //        public void run() {
    //            while (true){
    //                //获取订单，创建订单
    //                try {
    //                    VoucherOrder take = orderTasks.take();
    //                    //创建订单
    //                    handleVoucherOrder(take);
    //                } catch (Exception e) {
    //                    log.error("处理订单异常",e);
    //                }
    //
    //            }
    //        }
    //    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean b = lock.tryLock();//有看门狗自动续期，有默认ttl 有返回值，lock()无返回值

        if (!b) {
            log.error("一个只能购买一次");
            return;
        }
        try {
            proxy.createVoucherOrder2(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result secKill(Long voucherId) {
        // 1     执行lua脚本 //2     <>0 无资格，  ==0 有资格
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorks.nextId("order");

        Long result = stringRedisTemplate.execute(//执行脚本
                SECKILL_SCRIPT,
                Collections.emptyList(),//keys
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId));

        int r = result.intValue(); // 转为int
        /**
         * 成功返回0 1库存不足 2已下单
         */
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "已下单");
        }

        // 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单id
        return Result.ok(orderId);
    }

    //    @Override
    //    public Result secKill(Long voucherId) {
    //        //1     执行lua脚本 //2     <>0 无资格，  ==0 有资格
    //        Long userId = UserHolder.getUser().getId();
    //        Long result = stringRedisTemplate.execute(
    //                SECKILL_SCRIPT,
    //                Collections.emptyList(),
    //                voucherId.toString(), userId.toString());
    //        int r = result.intValue();//转为int
    //        if (r != 0) {
    //            return Result.fail(r == 1 ? "库存不足" : "已下单");
    //        }
    //        //有资格，订单保存到阻塞队列
    //        VoucherOrder voucherOrder = new VoucherOrder();
    //        long orderId = redisIdWorks.nextId("order");
    //        voucherOrder.setId(orderId);
    //        voucherOrder.setUserId(userId);
    //        voucherOrder.setVoucherId(voucherId);
    //        //加入队列
    //        orderTasks.add(voucherOrder);
    //        //获取代理对象
    //        proxy = (IVoucherOrderService) AopContext.currentProxy();
    //        //返回订单id
    //        return Result.ok(orderId);
    //    }

    //    @Override
    //    public Result secKill(Long voucherId) {
    //
    //        //1查询优惠卷
    //        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
    //        //2判断是否开始
    //        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
    //            //未开始
    //            return Result.fail("未开始");
    //        }
    //        //3判断是否结束
    //        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
    //            //结束
    //            return Result.fail("结束");
    //        }
    //        //4是否充足
    //        if (voucher.getStock() < 1) {
    //            //不足
    //            return Result.fail("库存不够");
    //        }
    //        Long userId = UserHolder.getUser().getId();
    //
    ////        synchronized (userId.toString().intern()){//只有先获取锁，提交事务，再释放锁，才安全，并且需要使用代理对象，事务才生效
    ////            //需要引入依赖 和 @EnableAspectJAutoProxy(exposeProxy = true)
    ////            IVoucherOrderService o = (IVoucherOrderService) AopContext.currentProxy();
    ////            return o.createVoucherOrder(voucherId);
    ////        }
    //
    //        //SimpleRedisLock lock = new SimpleRedisLock("order",stringRedisTemplate);
    //        RLock lock = redissonClient.getLock("lock:order:"+userId);
    //        //boolean b = lock.tryLock(2000L);
    //        boolean b = lock.tryLock();
    //        if (!b){
    //            return Result.fail("一个只能购买一次");
    //        }
    //        try {
    //            IVoucherOrderService o = (IVoucherOrderService) AopContext.currentProxy();
    //            return o.createVoucherOrder(voucherId);
    //        } finally {
    //            //lock.unLock();
    //            lock.unlock();
    //        }
    //    }

    @Transactional
    public void createVoucherOrder2(VoucherOrder voucherOrder) {
        Long voucherId = voucherOrder.getVoucherId();
        Long userId = voucherOrder.getUserId();
        int count = query().eq("voucher_id", voucherId).eq("user_id", userId).count();
        if (count > 0) {
            log.error("已购买，一人只能一单");
            return;
        }
        boolean success = iSeckillVoucherService
                .update() // 5扣减
                .setSql("stock=stock-1") // set条件
                .eq("voucher_id", voucherId) // where条件
                .gt("stock", 0) // 确保大于0即可
                .update();
        if (!success) {
            log.error("库存不足");
            return;
        }
        save(voucherOrder);
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // 充足，查询订单，根据用户id和优惠卷id，存在，返回，不存在则扣减
        // 一人一单
        Long userId = UserHolder.getUser().getId();
        int count = query().eq("voucher_id", voucherId).eq("user_id", userId).count();
        if (count > 0) {
            return Result.fail("已购买，一人只能一单");
        }
        // 5扣减
        boolean success = iSeckillVoucherService
                .update()
                .setSql("stock=stock-1") // set条件
                .eq("voucher_id", voucherId) // where条件
                // .eq("stock",voucher.getStock())//失败率高
                .gt("stock", 0) // 确保大于0即可
                .update();
        if (!success) {
            return Result.fail("库存不足");
        }
        // 6下单 订单id，用户id，优惠卷id
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorks.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        // 7返回订单id
        return Result.ok(orderId);
    }
}
